/**
 * 
 * 起迪科技 Copyright (c) 2014-2018 QiDi,Inc.All Rights Reserved.
 */

package cn.qidisoft.edu.hzjt.controller.zxjdifficultStudent;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.cxf.endpoint.Client;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cn.qidisoft.core.common.log.LoggerAdapter;
import cn.qidisoft.core.common.log.LoggerAdapterFactory;
import cn.qidisoft.core.common.pagination.Page;
import cn.qidisoft.core.common.pagination.PaginationBean;
import cn.qidisoft.core.util.StringUtils;
import cn.qidisoft.core.util.json.JsonBinder;
import cn.qidisoft.core.util.moffice.excel.ExpExcelUtil;
import cn.qidisoft.edu.hzjt.annotation.SysLogger;
import cn.qidisoft.edu.hzjt.constants.Constant;
import cn.qidisoft.edu.hzjt.controller.BaseController;
import cn.qidisoft.edu.hzjt.exception.RPCException;
import cn.qidisoft.edu.hzjt.model.ResponseResult;
import cn.qidisoft.edu.hzjt.model.Student;
import cn.qidisoft.edu.hzjt.model.StudentClass;
import cn.qidisoft.edu.hzjt.model.UserEmployee;
import cn.qidisoft.edu.hzjt.model.ZxjDifficultStudent;
import cn.qidisoft.edu.hzjt.service.ICommonService;
import cn.qidisoft.edu.hzjt.service.IZxjDifficultStudentService;
import cn.qidisoft.edu.hzjt.utils.AddSoapHeader;
import cn.qidisoft.edu.hzjt.utils.IdCardUtils;
import cn.qidisoft.edu.hzjt.utils.LogType;
import cn.qidisoft.edu.hzjt.utils.WsClientUrlConstants;
import cn.qidisoft.edu.hzjt.vo.FlowApprovalState;

/**
 * 
 * 
 * @author Administrator
 * @version $Id: ZxjDifficultStudentController.java, v 0.1 2018年11月1日 上午10:50:34 hhl Exp $
 */

@Controller
@RequestMapping(value = "zxjDifficultStudent")
public class ZxjDifficultStudentController {
    protected static final LoggerAdapter LOGGER = LoggerAdapterFactory
        .getLogger(LogType.HZJT_LOGGER.val);
    @Autowired
    private IZxjDifficultStudentService  zxjDifficultStudentService;

    @Autowired
    private ICommonService               commonService;

    @RequestMapping(value = "/index")
    public String index(ModelMap model, HttpServletRequest request) {
        try {
            request.setAttribute("msg", BaseController.getParameter("msg"));
            BaseController.removeParameter("msg");
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
        return "zxjDifficultStudent/zxjDifficultStudentList";
    }

    @RequestMapping(value = "/List")
    @ResponseBody
    public ResponseResult List(ModelMap model, HttpServletRequest request,
                               @RequestParam(value = "rows", required = false) String pageSize,
                               @RequestParam(value = "page", required = false) String currentPage,
                               ZxjDifficultStudent data) {

        try {
            Student student = (Student) request.getSession()
                .getAttribute(Constant.LOGIN_CONSOLE_USER);
            data.setStuid(student.getXsid());
            Page page = new Page();
            page.setCurrPage(currentPage == null ? 0 : Integer.valueOf(currentPage));
            page.setPageSize(pageSize == null ? Constant.PageSize : Integer.valueOf(pageSize));
            BaseController.setSortByColumn(request, "createtime", "desc");
            data.setOrderField((String) request.getAttribute("orderField"));
            data.setOrderFlag((String) request.getAttribute("orderFlag"));

            PaginationBean<ZxjDifficultStudent> paginationBean = zxjDifficultStudentService
                .queryPageList(data, page);
            ResponseResult result = new ResponseResult();
            if (paginationBean.getPageList().isEmpty()) {
                result.setRows(new ArrayList<ZxjDifficultStudent>());
            } else {
                result.setRows(paginationBean.getPageList());
            }
            result.setTotal(paginationBean.getTotalRecords());
            return result;
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return null;
    }

    @RequestMapping(value = "/addInInt", method = RequestMethod.GET)
    public String add(ModelMap model, HttpServletRequest request) {
        try {
            Integer loginType = (Integer) request.getSession()
                .getAttribute(Constant.LOGIN_USER_TYPE);
            if (loginType == 1) { // 学生
                Student student = (Student) request.getSession()
                    .getAttribute(Constant.LOGIN_CONSOLE_USER);
                // 获取标准信息
                BaseController.getNationList(model, commonService, Constant.MZ_CODE); // 民族
                BaseController.getCodeList(model, commonService, Constant.ZZMM_CODE); // 政治面貌
                if (student.getCsrq() == null || student.getCsrq().equals("")) {
                    student.setCsrq1(IdCardUtils.getIdCardBirthday(student.getSfzh()));
                } else {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    student.setCsrq1(sdf.format(student.getCsrq()));
                }

                model.put("student", student);
                model.put("msg", BaseController.getParameter("msg"));
                BaseController.removeParameter("msg");
            } else {
                BaseController.setParameter("msg", "没权限访问该页面");
                return "redirect:index";
            }
            request.setAttribute("msg", BaseController.getParameter("msg"));
            BaseController.removeParameter("msg");
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
        return "zxjDifficultStudent/add_ZxjDifficultStudent";
    }

    @RequestMapping(value = "/details", method = RequestMethod.GET)
    public String details(ModelMap model, HttpServletRequest request,
                          @RequestParam(value = "id", required = false) Integer id,
                          @RequestParam(value = "gid", required = false) String gid) {
        try {

            ZxjDifficultStudent data = new ZxjDifficultStudent();
            data.setKnid(id);
            data.setGid(gid);
            data = zxjDifficultStudentService.queryByPK(data);

            BaseController.getNationList(model, commonService, Constant.MZ_CODE); // 民族
            BaseController.getCodeList(model, commonService, Constant.ZZMM_CODE); // 政治面貌
            if (data.getCsrq() == null || data.getCsrq().equals("")) {
                data.setCsrq1(IdCardUtils.getIdCardBirthday(data.getSfzh()));
            } else {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                data.setCsrq1(sdf.format(data.getCsrq()));
            }
            model.addAttribute("data", data);

            Student student = (Student) request.getSession()
                .getAttribute(Constant.LOGIN_CONSOLE_USER);

            List<ZxjDifficultStudent> chekResultList = new ArrayList<ZxjDifficultStudent>();
            if (data != null && data.getStates() != FlowApprovalState.state0.getIndex()) {
                // 审批流程记录信息
                Client client = AddSoapHeader
                    .validateClient(WsClientUrlConstants.WS_FLOW_FACADE_REMOTE, student.getXh());
                if (client != null) {
                    Object[] object = new Object[] { id + "",
                                                     WsClientUrlConstants.XGGL_ZXJ_KNSRD_CELL_ID,
                                                     true };
                    Object[] results = client.invoke("GetCustomAuditResults", object);
                    if (results != null && results.length >= 1) {
                        JSONObject jsonObject = (JSONObject) JSON.parse((String) results[0]);
                        if (jsonObject.get("data") != null) {
                            chekResultList = JSON.parseArray(jsonObject.get("data").toString(),
                                ZxjDifficultStudent.class);
                        }
                    }
                }
            }
            model.put("chekResultList", chekResultList);
            request.setAttribute("msg", BaseController.getParameter("msg"));
            BaseController.removeParameter("msg");

            return "zxjDifficultStudent/details_ZxjDifficultStudent";
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("查询 queryByPK [{}] error," + this.getClass().getName() + "=[{}]",
                this.getClass().getName(), e.getMessage());
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
    }

    @SysLogger(description = "困难生认定管理信息", moduleName = "困难生认定管理", method = "新增保存")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String add(ModelMap model, HttpServletRequest request, ZxjDifficultStudent data) {
        try {
            data.setCreatetime(new Date());
            if (data.getDbz() == null) {
                data.setDbz(false);
            }
            if (data.getFljgzm() == null) {
                data.setFljgzm(false);
            }
            if (data.getGmlszn() == null) {
                data.setGmlszn(false);
            }
            if (data.getWbgydx() == null) {
                data.setWbgydx(false);
            }
            if (data.getCjz() == null) {
                data.setCjz(false);
            }
            if (data.getSqzm() == null) {
                data.setSqzm(false);
            }
            if (data.getQtzj() == null) {
                data.setQtzj(false);
            }
            String gid = zxjDifficultStudentService.add(data);

            model.addAttribute("gid", gid);
            return "redirect:/zxjDifficultStudent/details";
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
    }

    @SysLogger(description = "困难生认定管理信息", moduleName = "困难生认定管理", method = "新增保存")
    @RequestMapping(value = "/addSaveContinue", method = RequestMethod.POST)
    public String addSaveContinue(ModelMap model, HttpServletRequest request,
                                  ZxjDifficultStudent data) {
        try {
            data.setCreatetime(new Date());
            if (data.getDbz() == null) {
                data.setDbz(false);
            }
            if (data.getFljgzm() == null) {
                data.setFljgzm(false);
            }
            if (data.getGmlszn() == null) {
                data.setGmlszn(false);
            }
            if (data.getWbgydx() == null) {
                data.setWbgydx(false);
            }
            if (data.getCjz() == null) {
                data.setCjz(false);
            }
            if (data.getSqzm() == null) {
                data.setSqzm(false);
            }
            if (data.getQtzj() == null) {
                data.setQtzj(false);
            }

            zxjDifficultStudentService.add(data);

            BaseController.setParameter("msg", "添加成功");
            return "redirect:addInInt";
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("添加信息 add [{}] error," + this.getClass().getName() + "=[{}]",
                this.getClass().getName(), e.getMessage());
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
    }

    @SysLogger(description = "困难生认定管理信息", moduleName = "困难生认定管理", method = "提交")
    @RequestMapping(value = "/btnSubmit")
    public String btnSubmit(ModelMap model, HttpServletRequest request,
                            @RequestParam(value = "id", required = false) Integer id) {
        /*try {
           ZxjDifficultStudent data = new ZxjDifficultStudent();
            data.setKnid(id);
            data = zxjDifficultStudentService.queryByPK(data);
            data.setStates(2);
            zxjDifficultStudentService.update(data);
        
            model.addAttribute("id", id);
            return "redirect:/zxjDifficultStudent/details";
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }*/

        Integer loginType = (Integer) request.getSession().getAttribute(Constant.LOGIN_USER_TYPE);
        try {
            if (loginType == 1) { // 学生
                Student student = (Student) request.getSession()
                    .getAttribute(Constant.LOGIN_CONSOLE_USER);
                if (id >= 1) {
                    Client client = AddSoapHeader.validateClient(
                        WsClientUrlConstants.WS_FLOW_FACADE_REMOTE, student.getXh());
                    if (client != null) {
                        ZxjDifficultStudent data = new ZxjDifficultStudent();
                        data.setKnid(id);
                        data = zxjDifficultStudentService.queryByPK(data);
                        HashMap<String, Object> conditionDataMap = new HashMap<String, Object>();

                        conditionDataMap.put("xm", student.getXm());
                        conditionDataMap.put("xh", student.getXh());
                        conditionDataMap.put("hjszd", data.getHjszd());
                        conditionDataMap.put("mz", data.getMz());

                        conditionDataMap.put("bjid", student.getBjid());
                        conditionDataMap.put("bjmc", student.getBjmc());
                        conditionDataMap.put("njid", student.getNjid());
                        conditionDataMap.put("njmc", student.getNjmc());
                        conditionDataMap.put("zyid", student.getZyid());
                        conditionDataMap.put("zymc", student.getZymc());

                        Object[] object = new Object[] { WsClientUrlConstants.XGGL_ZXJ_KNSRD_CELL_ID,
                                                         id + "", true, null,
                                                         JsonBinder.toJson(conditionDataMap) };
                        data.setStates(FlowApprovalState.state2.getIndex());
                        int num = zxjDifficultStudentService.update(data);
                        if (num >= 1) { // 提交成功
                            Object[] results = client.invoke("SubmitFlow", object);
                            if (results == null || results.length == 0) {
                                data.setStates(FlowApprovalState.state0.getIndex());
                                zxjDifficultStudentService.update(data);
                                BaseController.setParameter("msg", "调用流程中发生了服务器异常，提交申请信息失败");
                            } else {
                                JSONObject jsonObject = (JSONObject) JSON
                                    .parse((String) results[0]);
                                if (!"success".equals(jsonObject.get("status"))) {
                                    data.setStates(FlowApprovalState.state0.getIndex());
                                    zxjDifficultStudentService.update(data);
                                } else {
                                    BaseController.setParameter("msg", "提交成功");
                                }
                            }
                        } else {
                            BaseController.setParameter("msg", "提交失败");
                        }
                    }
                    return "redirect:details?id=" + id;
                }

            } else {
                BaseController.setParameter("msg", "您没权限访问该页面");
                return "redirect:/index";
                // model.addAttribute("id", id);
                // return "redirect:/twglStudentCorporation/details";
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
        return null;
    }

    @SysLogger(description = "困难生认定管理信息", moduleName = "困难生认定管理", method = "提交")
    @RequestMapping(value = "/updatebtnSubmit")
    public String updatebtnSubmit(ModelMap model, HttpServletRequest request,
                                  ZxjDifficultStudent data) {
        try {
            data.setCreatetime(new Date());
            zxjDifficultStudentService.update(data);

            model.addAttribute("id", data.getKnid());
            return "redirect:/zxjDifficultStudent/details";
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
    }

    @RequestMapping(value = "/updateToview", method = RequestMethod.GET)
    public String updateToview(ModelMap model, HttpServletRequest request,
                               @RequestParam(value = "id") Integer id) {
        try {

            ZxjDifficultStudent data = new ZxjDifficultStudent();
            data.setKnid(id);
            data = zxjDifficultStudentService.queryByPK(data);

            BaseController.getNationList(model, commonService, Constant.MZ_CODE); // 民族
            BaseController.getCodeList(model, commonService, Constant.ZZMM_CODE); // 政治面貌
            if (data.getCsrq() == null || data.getCsrq().equals("")) {
                data.setCsrq1(IdCardUtils.getIdCardBirthday(data.getSfzh()));
            } else {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                data.setCsrq1(sdf.format(data.getCsrq()));
            }

            model.addAttribute("data", data);
            return "zxjDifficultStudent/update_ZxjDifficultStudent";
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("查询 queryByPK [{}] error," + this.getClass().getName() + "=[{}]",
                this.getClass().getName(), e.getMessage());
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
    }

    @SysLogger(description = "困难生认定管理信息", moduleName = "困难生认定管理", method = "修改")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String update(ModelMap model, HttpServletRequest request, ZxjDifficultStudent data) {
        try {

            if (data.getDbz() == null) {
                data.setDbz(false);
            }
            if (data.getFljgzm() == null) {
                data.setFljgzm(false);
            }
            if (data.getGmlszn() == null) {
                data.setGmlszn(false);
            }
            if (data.getWbgydx() == null) {
                data.setWbgydx(false);
            }
            if (data.getCjz() == null) {
                data.setCjz(false);
            }
            if (data.getSqzm() == null) {
                data.setSqzm(false);
            }
            if (data.getQtzj() == null) {
                data.setQtzj(false);
            }
            zxjDifficultStudentService.update(data);
            BaseController.setParameter("msg", "保存成功");
            return "redirect:index";
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("查询 update [{}] error," + this.getClass().getName() + "=[{}]",
                this.getClass().getName(), e.getMessage());
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
    }

    @SysLogger(description = "困难生认定管理信息", moduleName = "困难生认定管理", method = "删除")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public String delete(ModelMap model, HttpServletRequest request) {
        try {
            String[] idList = request.getParameter("idList").split(",");
            ZxjDifficultStudent data = new ZxjDifficultStudent();
            data.setIds(idList);
            zxjDifficultStudentService.delete(data);
            BaseController.setParameter("msg", "删除成功");
            return "redirect:index";
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("删除 delete [{}] error," + this.getClass().getName() + "=[{}]",
                this.getClass().getName(), e.getMessage());
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
    }

    /**
     * 管理端
     * 
     * @param model
     * @param request
     * @return
     */

    @RequestMapping(value = "/index_admin")
    public String index_admin(ModelMap model, HttpServletRequest request) {
        try {
            // 获得年级信息
            BaseController.getGradeList(model, commonService);
            // 获得专业
            BaseController.getSpecialityList(model, commonService);
            Student student = new Student();
            List<StudentClass> classList = commonService.queryGradeSpecialtyByClass(student);
            model.put("classList", classList);
            Integer loginType = (Integer) request.getSession()
                .getAttribute(Constant.LOGIN_USER_TYPE);
            BaseController.getClassListAndBzrid(request, model, commonService, loginType);

        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }

        return "zxjDifficultStudent/zxjDifficultStudentList_admin";
    }

    @RequestMapping(value = "/List_admin")
    @ResponseBody
    public ResponseResult List_admin(ModelMap model, HttpServletRequest request,
                                     @RequestParam(value = "rows", required = false) String pageSize,
                                     @RequestParam(value = "page", required = false) String currentPage,
                                     ZxjDifficultStudent data) {

        try {
            UserEmployee userEmployee = (UserEmployee) request.getSession()
                .getAttribute(Constant.LOGIN_CONSOLE_USER);
            if (data.getIsmanager() != null && data.getIsmanager().intValue() == 1) {
                data.setEmid(userEmployee.getEmid());
            } else {
                data.setEmid(null);
            }
            Page page = new Page();
            page.setCurrPage(currentPage == null ? 0 : Integer.valueOf(currentPage));
            page.setPageSize(pageSize == null ? Constant.PageSize : Integer.valueOf(pageSize));
            BaseController.setSortByColumn(request, "createtime", "desc");
            data.setOrderField((String) request.getAttribute("orderField"));
            data.setOrderFlag((String) request.getAttribute("orderFlag"));
            data.setLogo("100"); // 标识管理端

            PaginationBean<ZxjDifficultStudent> paginationBean = zxjDifficultStudentService
                .queryPageList(data, page);
            ResponseResult result = new ResponseResult();
            if (paginationBean.getPageList().isEmpty()) {
                result.setRows(new ArrayList<ZxjDifficultStudent>());
            } else {
                result.setRows(paginationBean.getPageList());
            }
            result.setTotal(paginationBean.getTotalRecords());
            return result;
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 管理端下载
     * 
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/export_admin")
    public @ResponseBody String export_admin(HttpServletRequest request,
                                             HttpServletResponse response, ZxjDifficultStudent data,
                                             @RequestParam("bodyData") String bodyData,
                                             ModelMap model) throws Exception {
        try {

            UserEmployee userEmployee = (UserEmployee) request.getSession()
                .getAttribute(Constant.LOGIN_CONSOLE_USER);
            if (data.getIsmanager() != null && data.getIsmanager().intValue() == 1) {
                data.setEmid(userEmployee.getEmid());
            } else {
                data.setEmid(null);
            }
            BaseController.setSortByColumn(request, "createtime", "desc");
            data.setOrderField((String) request.getAttribute("orderField"));
            data.setOrderFlag((String) request.getAttribute("orderFlag"));
            data.setLogo("100"); // 标识管理端
            List<ZxjDifficultStudent> datalist = zxjDifficultStudentService.export(data);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            String[][] title_name = { { "姓名", "学号", "班级", "专业", "年级", "认定结果", "认定时间" } };
            String[] title_style = { "hwzs_16_bold_25", "kt_12_bold_18", "st_12_r_20", "st_12_n_20",
                                     "st_12_n_20", "st_12_n_20", "st_12_n_20" };
            String fileName = "困难生认定信息";
            String[] remark = { "" };
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            /*  List<ZxjDifficultStudent> datalist = JSONArray.parseArray(bodyData,
                ZxjDifficultStudent.class);*/
            if (datalist != null && !datalist.isEmpty()) {
                for (ZxjDifficultStudent r : datalist) {
                    Map<String, Object> map = new LinkedHashMap<String, Object>();
                    map.put("xm", r.getXm());
                    map.put("xh", r.getXh());
                    map.put("bj", r.getBjmc());
                    map.put("zy", r.getZymc());
                    map.put("njmc", r.getNjmc());
                    map.put("zzrdjg", r.getZzrdjg());
                    if (r.getCreatetime() == null) {
                        map.put("ksrq", null);
                    } else {
                        map.put("ksrq", sdf.format(r.getCreatetime()));
                    }

                    list.add(map);
                }
            }
            HSSFWorkbook wb = ExpExcelUtil.getWorkBookExcel(title_name, title_style, 100, remark,
                fileName, list);
            try {
                String filenameConvert = "困难生认定信息";/* new String(fileName.getBytes("GB2312"), "ISO8859-1"); */
                response.reset();
                response.setContentType("application/vnd.ms-excel;charset=utf-8");
                response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String((filenameConvert + ".xls").getBytes(),
                        "iso-8859-1"));
                response.setDateHeader("Expires", 0);
                ServletOutputStream os = response.getOutputStream();
                wb.write(os);
                os.flush();
            } catch (Exception e) {
                System.out.println("网络连接断开，可能用户取消了导出");
                model.addAttribute(Constant.EXPTION_MSG_KEY, e);
                return "error/error";
            }
        } catch (RPCException e) {
            LOGGER.error("获得信息 export[{}] error," + this.getClass().getName() + "=[{}]",
                this.getClass().getName(), e.getMessage());
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
        return null;
    }

    // 审核端
    @RequestMapping(value = "/index_audit")
    public String index_audit(ModelMap model, HttpServletRequest request) {
        try {
            // model.addAttribute("states", 1);
            // 获得年级信息
            BaseController.getGradeList(model, commonService);
            // 获得专业
            BaseController.getSpecialityList(model, commonService);
            Student student = new Student();
            List<StudentClass> classList = commonService.queryGradeSpecialtyByClass(student);
            model.put("classList", classList);

            request.setAttribute("msg", BaseController.getParameter("msg"));
            BaseController.removeParameter("msg");
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
        return "zxjDifficultStudent/zxjDifficultStudentList_audit";
    }

    @RequestMapping(value = "/List_audit")
    @ResponseBody
    public ResponseResult List_audit(ModelMap model, HttpServletRequest request,
                                     @RequestParam(value = "rows", required = false) String pageSize,
                                     @RequestParam(value = "page", required = false) String currentPage,
                                     ZxjDifficultStudent data) {

        /*  data.setLogo("99"); // 标识审核管理端
        try {
            Page page = new Page();
            page.setCurrPage(currentPage == null ? 0 : Integer.valueOf(currentPage));
            page.setPageSize(pageSize == null ? Constant.PageSize : Integer.valueOf(pageSize));
            BaseController.setSortByColumn(request, "createtime", "desc");
            data.setOrderField((String) request.getAttribute("orderField"));
            data.setOrderFlag((String) request.getAttribute("orderFlag"));
        
            PaginationBean<ZxjDifficultStudent> paginationBean = zxjDifficultStudentService
                .queryPageList(data, page);
            ResponseResult result = new ResponseResult();
            result.setTotal(paginationBean.getTotalRecords());
            result.setRows(paginationBean.getPageList());
            return result;
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return null;*/
        if (data.getDdlStepState() == null || data.getDdlStepState().equals("")) {
            data.setDdlStepState("2");
        } else if (data.getDdlStepState() != null && data.getDdlStepState().equals("-1")) {
            data.setDdlStepState(null);
        }

        if (data.getDdlUserState() == null || data.getDdlUserState().equals("")) {
            data.setDdlUserState("0");
        } else if (data.getDdlUserState() != null && data.getDdlUserState().equals("-1")) {
            data.setDdlUserState(null);
        }

        Integer loginType = (Integer) request.getSession().getAttribute(Constant.LOGIN_USER_TYPE);
        try {
            ResponseResult result = new ResponseResult();
            List<ZxjDifficultStudent> pageList = new ArrayList<ZxjDifficultStudent>();
            int totalRecords = 0;
            if (loginType == 2) { // 老师
                UserEmployee userEmployee = (UserEmployee) request.getSession()
                    .getAttribute(Constant.LOGIN_CONSOLE_USER);
                String params = validateQueryParams(data);

                Client client = AddSoapHeader.validateClient(
                    WsClientUrlConstants.WS_FLOW_FACADE_REMOTE, userEmployee.getUserid());
                if (client != null) {
                    Page page = BaseController.getPage(currentPage, pageSize, request,
                        "reSubmitTime", "desc");
                    Object[] object = new Object[] { WsClientUrlConstants.XGGL_ZXJ_KNSRD_CELL_ID,
                                                     page.getCurrPage(), page.getPageSize(), params,
                                                     (String) request.getAttribute(
                                                         "orderField") + " " + (String) request
                                                             .getAttribute("orderFlag") };
                    Object[] results = client.invoke("GetUserAuditFlowData_LowerOrder", object);
                    if (results == null || results.length == 0) {
                        //  BaseController.setParameter("msg", "调用流程中发生了服务器异常");
                    } else {
                        JSONObject jsonObject = (JSONObject) JSON.parse((String) results[0]);
                        if (!"success".equals(jsonObject.get("status"))) {
                            result.setMsg(jsonObject.get("errMsg"));
                        } else {
                            if (jsonObject.get("rowCount") != null) {
                                totalRecords = (int) jsonObject.get("rowCount");
                            }
                            if (jsonObject.get("data") != null) {
                                pageList = JSON.parseArray(String.valueOf(jsonObject.get("data")),
                                    ZxjDifficultStudent.class);
                                totalRecords = pageList.size();
                            }
                        }
                    }
                    // PaginationBean<ZxjDifficultStudent> paginationBean =
                    // dataService.queryZxjDifficultStudentAuditPageList(data, page);
                    result.setTotal(totalRecords);
                    result.setRows(pageList);
                    return result;
                }
            }

        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 获得查询条件
     * 
     * @param data
     * @return
     */
    private static String validateQueryParams(ZxjDifficultStudent data) {
        HashMap<String, Object> conditionDataMapList = new HashMap<String, Object>();
        StringBuilder sb = new StringBuilder(200);
        String paramString = null;
        sb.append("[");
        boolean ok = true;
        if (!StringUtils.isNullValue(data.getDdlStates())) {
            conditionDataMapList.clear();
            conditionDataMapList.put("FieldName", "Sys_ApprovalInfo.flowState");
            conditionDataMapList.put("Value", data.getDdlStates());
            conditionDataMapList.put("NeedQuotes", true); // 是否需要单引号
            sb.append(JsonBinder.toJson(conditionDataMapList)).append(",");
            ok = false;
        }
        if (!StringUtils.isNullValue(data.getDdlStepState())) {
            conditionDataMapList.clear();
            conditionDataMapList.put("FieldName", "Sys_ApprovalInfoStep.stepState");
            conditionDataMapList.put("Value", data.getDdlStepState());
            conditionDataMapList.put("NeedQuotes", true); // 是否需要单引号
            sb.append(JsonBinder.toJson(conditionDataMapList)).append(",");
            ok = false;
        }
        if (!StringUtils.isNullValue(data.getDdlUserState())) {
            conditionDataMapList.clear();
            conditionDataMapList.put("FieldName", "Sys_ApprovalInfoResult.userState");
            conditionDataMapList.put("Value", data.getDdlUserState());
            conditionDataMapList.put("NeedQuotes", true); // 是否需要单引号
            sb.append(JsonBinder.toJson(conditionDataMapList)).append(",");
            ok = false;
        }
        if (!StringUtils.isNullValue(data.getXh())) {
            conditionDataMapList.clear();
            conditionDataMapList.put("FieldName", "xh");
            conditionDataMapList.put("Value", data.getXh());
            conditionDataMapList.put("Operator", "Like");
            sb.append(JsonBinder.toJson(conditionDataMapList)).append(",");
            ok = false;
        }
        if (!StringUtils.isNullValue(data.getXm())) {
            conditionDataMapList.clear();
            conditionDataMapList.put("FieldName", "xm");
            conditionDataMapList.put("Value", data.getXm());
            conditionDataMapList.put("Operator", "Like");
            sb.append(JsonBinder.toJson(conditionDataMapList)).append(",");
            ok = false;
        }

        if (data.getNjid() != null) {
            conditionDataMapList.clear();
            conditionDataMapList.put("FieldName", "njid");
            conditionDataMapList.put("Value", data.getNjid());
            conditionDataMapList.put("NeedQuotes", true); // 是否需要单引号
            sb.append(JsonBinder.toJson(conditionDataMapList)).append(",");
            ok = false;
        }
        if (data.getZyid() != null) {
            conditionDataMapList.clear();
            conditionDataMapList.put("FieldName", "zyid");
            conditionDataMapList.put("Value", data.getZyid());
            conditionDataMapList.put("NeedQuotes", true); // 是否需要单引号
            sb.append(JsonBinder.toJson(conditionDataMapList)).append(",");
            ok = false;
        }
        if (data.getBjid() != null) {
            conditionDataMapList.clear();
            conditionDataMapList.put("FieldName", "bjid");
            conditionDataMapList.put("Value", data.getBjid());
            conditionDataMapList.put("NeedQuotes", true); // 是否需要单引号
            sb.append(JsonBinder.toJson(conditionDataMapList)).append(",");
            ok = false;
        }
        if (ok == true) {
            return paramString;
        } else {
            if (sb.length() >= 2) {
                paramString = sb.substring(0, sb.length() - 1);
            }
            paramString = paramString + "]";
        }
        return paramString;
    }

    @RequestMapping(value = "/details_audit", method = RequestMethod.GET)
    public String details_admin(ModelMap model, HttpServletRequest request,
                                @RequestParam(value = "id", required = false) Integer id,
                                @RequestParam(value = "gid", required = false) String gid) {
        try {

            ZxjDifficultStudent data = new ZxjDifficultStudent();
            data.setKnid(id);
            data = zxjDifficultStudentService.queryByPK(data);

            BaseController.getNationList(model, commonService, Constant.MZ_CODE); // 民族
            BaseController.getCodeList(model, commonService, Constant.ZZMM_CODE); // 政治面貌
            if (data.getCsrq() == null || data.getCsrq().equals("")) {
                data.setCsrq1(IdCardUtils.getIdCardBirthday(data.getSfzh()));
            } else {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                data.setCsrq1(sdf.format(data.getCsrq()));
            }
            model.addAttribute("data", data);

            UserEmployee userEmployee = (UserEmployee) request.getSession()
                .getAttribute(Constant.LOGIN_CONSOLE_USER);
            // 获得审批记录信息
            List<ZxjDifficultStudent> chekResultList = new ArrayList<ZxjDifficultStudent>();
            String appId = request.getParameter("appId");
            String reId = request.getParameter("reId");
            Integer checkFlag = 0;
            if (!StringUtils.isNullValue(appId)) {
                Client client = AddSoapHeader.validateClient(
                    WsClientUrlConstants.WS_FLOW_FACADE_REMOTE, userEmployee.getUserid());
                if (client != null) {
                    Object[] object = new Object[] { Integer.parseInt(appId), true };
                    Object[] results = client.invoke("GetAdminAuditResults", object);
                    if (results != null && results.length >= 1) {
                        JSONObject jsonObject = (JSONObject) JSON.parse((String) results[0]);
                        if (jsonObject.get("data") != null) {
                            chekResultList = JSON.parseArray(jsonObject.get("data").toString(),
                                ZxjDifficultStudent.class);
                        }
                    }
                }

                // 获得当前用户是否审批过,根据状态
                if (!StringUtils.isNullValue(reId)) {
                    Object[] object2 = new Object[] { reId };
                    Object[] results2 = client.invoke("GetFlowAuditInfo", object2);
                    if (results2 != null && results2.length >= 1) {
                        JSONObject jsonObject2 = (JSONObject) JSON.parse((String) results2[0]);
                        if (jsonObject2.get("userIsAuditing") != null) {
                            if ((boolean) jsonObject2.get("userIsAuditing") == true) {
                                checkFlag = 1; // 可以审核
                            } else {
                                checkFlag = 0; // 可以审核
                            }
                        }
                    }
                }

            }

            UserEmployee userEmployee1 = new UserEmployee();
            userEmployee1.setUid(userEmployee.getUid()/*1615*/);
            int count = commonService.queryUserClassByValdateBzr(userEmployee1);
            if (count >= 1) {
                model.put("isbzr", true);
            } else {
                model.put("isbzr", false);
            }

            model.put("chekResultList", chekResultList);
            model.put("reId", request.getParameter("reId"));
            model.put("checkFlag", checkFlag);

            return "zxjDifficultStudent/zxjDifficultStudent_registration_audit";
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("查询 queryByPK [{}] error," + this.getClass().getName() + "=[{}]",
                this.getClass().getName(), e.getMessage());
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
    }

    @RequestMapping(value = "/audit")
    @SysLogger(description = "困难生认定管理信息", moduleName = "困难生认定管理信息", method = "审核")
    public String audit(ModelMap model, HttpServletRequest request,
                        @RequestParam(value = "knid") Integer knid,
                        @RequestParam(value = "states") Integer states,
                        @RequestParam(value = "reId") Integer reId) {
        Integer loginType = (Integer) request.getSession().getAttribute(Constant.LOGIN_USER_TYPE);
        try {
            if (loginType == 2) { // 老师
                UserEmployee userEmployee = (UserEmployee) request.getSession()
                    .getAttribute(Constant.LOGIN_CONSOLE_USER);
                if (knid >= 1) {
                    // 审批流程
                    Client client = AddSoapHeader.validateClient(
                        WsClientUrlConstants.WS_FLOW_FACADE_REMOTE, userEmployee.getUserid());
                    ZxjDifficultStudent data = new ZxjDifficultStudent();
                    data.setKnid(knid);
                    boolean bool = false; // 流程是否结束
                    if (client != null) {
                        String spyj = request.getParameter("spyj");
                        Object[] object = new Object[] { reId, states == 3 ? true : false, spyj,
                                                         null };
                        Object[] results = client.invoke("DoAudit", object);
                        if (results != null && results.length >= 1) {
                            JSONObject jsonObject = (JSONObject) JSON.parse((String) results[0]);
                            if (jsonObject.get("success") != null
                                && true == (boolean) jsonObject.get("success")) { // 流程审核通过
                                if (jsonObject.get("flowFinished") != null
                                    && true == (boolean) jsonObject.get("flowFinished")
                                    && jsonObject.get("flowState") != null
                                    && ((Integer) jsonObject.get("flowState"))
                                        .intValue() == (FlowApprovalState.state3.getIndex())
                                            .intValue()) { // 标识流程结束，将数据库状态修改成审核通过
                                    data.setBzrrdjg(request.getParameter("bzrrdjg"));
                                    data.setZzrdjg(request.getParameter("zzrdjg"));
                                    data.setStates(FlowApprovalState.state3.getIndex());
                                    bool = true;
                                } else if (jsonObject.get("flowFinished") != null
                                           && false == (boolean) jsonObject.get("flowFinished")
                                           && jsonObject.get("flowState") != null
                                           && ((Integer) jsonObject.get("flowState"))
                                               .intValue() == (FlowApprovalState.state1.getIndex())
                                                   .intValue()) {
                                    data.setBzrrdjg(request.getParameter("bzrrdjg"));
                                    data.setZzrdjg(request.getParameter("zzrdjg"));
                                    data.setStates(FlowApprovalState.state1.getIndex());
                                    bool = true;
                                } else if (jsonObject.get("flowFinished") != null
                                           && false == (boolean) jsonObject.get("flowFinished")
                                           && jsonObject.get("flowState") != null
                                           && ((Integer) jsonObject.get("flowState"))
                                               .intValue() == (FlowApprovalState.state2.getIndex())
                                                   .intValue()) {
                                    data.setBzrrdjg(request.getParameter("bzrrdjg"));
                                    data.setZzrdjg(request.getParameter("zzrdjg"));
                                    data.setStates(FlowApprovalState.state2.getIndex());
                                    bool = true;
                                } else if (jsonObject.get("flowFinished") != null
                                           && false == (boolean) jsonObject.get("flowFinished")
                                           && jsonObject.get("flowState") != null
                                           && ((Integer) jsonObject.get("flowState"))
                                               .intValue() == (FlowApprovalState.state8.getIndex())
                                                   .intValue()) {
                                    data.setBzrrdjg(request.getParameter("bzrrdjg"));
                                    data.setZzrdjg(request.getParameter("zzrdjg"));
                                    data.setStates(FlowApprovalState.state8.getIndex());
                                    bool = true;
                                } else {
                                    bool = false; // 标识流程审核未结束
                                }
                                if (bool == true) { // 代表流程结束后才能将数据状态更新
                                    int num = zxjDifficultStudentService.audit(data);
                                    if (num >= 1) {
                                        BaseController.setParameter("msg", "审核成功");
                                    } else {
                                        BaseController.setParameter("msg", "审核失败");
                                    }
                                }
                            } else {
                                BaseController.setParameter("msg", "审核失败");
                            }

                        } else {
                            BaseController.setParameter("msg", "流程服务器异常，未返回结果信息，审核失败");
                        }
                    }
                } else {
                    BaseController.setParameter("msg", "审核的数据不存在");
                }
            } else {
                BaseController.setParameter("msg", "没权限访问该页面");
            }
            return "redirect:index_audit";
        } catch (Exception e) {
            LOGGER.error("老师审核助学金申请信息 audit [{}] error," + this.getClass().getName() + "=[{}]",
                this.getClass().getName(), e.getMessage());
            model.addAttribute(Constant.EXPTION_MSG_KEY, e);
            return "error/error";
        }
    }

}
